<?php
/**
 * Cache clean-up script for cron.
 *
 * @version 2010-08-10
 */

require_once dirname(__FILE__) . '/../config.php';
if (Config::MAX_CACHE_SIZE == -1) { // unlimited cache size
    exit();
}

require_once Config::ROOT . '/libs/FTP.php';

$caches = array('db', 'img', 'output');
$limits = array(Config::CACHE_DB_TIMEOUT, Config::CACHE_IMAGE_TIMEOUT,
        Config::CACHE_OUTPUT_TIMEOUT);

foreach ($caches as $key => $cache) {
    if (checkCache($cache)) {
        cleanCache($cache, $limits[$key]);
    }
}

function cleanCache($type, $limit) {
    $content = glob(Config::ROOT . "/cache/$type/*");
    if (!is_array($content)) {
        return;
    }
    $timeLimit = time() - $limit;
    $len = strlen(Config::ROOT);
    foreach ($content as $file) {
        if (filectime($file) < $timeLimit) {
            FTP::deleteFile(substr($file, $len));
        }
    }
}

function checkCache($type) {
    if (Config::MAX_CACHE_SIZE == 0) {
        return false;
    }
    $content = glob(Config::ROOT . "/cache/$type/*");
    if (!is_array($content)) {
        return false;
    }
    return count($content) > Config::MAX_CACHE_SIZE;
}
?>
